package com.seecen.webproject.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecen.webproject.entity.User;
import com.seecen.webproject.exception.PasswordNotMatchException;
import com.seecen.webproject.exception.UserNameNotFountException;
import com.seecen.webproject.service.UserService;
import com.seecen.webproject.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginController extends HttpServlet {
    private UserService userService = new UserService();
    ObjectMapper objectMapper = new ObjectMapper();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setUsername(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        Result result = null;
        try {
            // 调用service层的方法，完成登录
            User dbUser = userService.login(user);
            result = Result.success(dbUser);
        } catch (UserNameNotFountException e) {
            result = Result.fail(Result.FAIL_CODE, "用户名不存在！");
        } catch (PasswordNotMatchException e) {
            result = Result.fail(Result.FAIL_CODE, "密码错误！");
        }
        // 将对象转换成json字符串
        String jsonStr = objectMapper.writeValueAsString(result);
        // 响应给前端
        response.getWriter().println(jsonStr);
    }
}
